package com.example.educationai.controller;

import com.example.educationai.entity.Exam;
import com.example.educationai.entity.ExamRecord;
import com.example.educationai.entity.ClassEntity;
import com.example.educationai.entity.SimpleUser;
import com.example.educationai.entity.SimpleUser.UserRole;
import com.example.educationai.service.ExamService;
import com.example.educationai.service.ExamRecordService;
import com.example.educationai.service.ClassService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import java.time.LocalDateTime;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Controller
@RequestMapping("/exam")
public class ExamController {

    private static final Logger log = LoggerFactory.getLogger(ExamController.class);

    @Autowired
    private ExamService examService;
    
    @Autowired
    private ExamRecordService examRecordService;
    
    @Autowired
    private ClassService classService;

    @GetMapping("/list")
    public String listExams(Model model, HttpSession session) {
        SimpleUser user = (SimpleUser) session.getAttribute("user");
        if (user == null) {
            return "redirect:/simple-login";
        }
        
        if (UserRole.TEACHER.equals(user.getRole())) {
            List<ClassEntity> classes = classService.getTeacherClasses(user);
            model.addAttribute("classes", classes);
            model.addAttribute("currentPage", "grade");
            return "exam/teacher-list";
        } else {
            // 学生查看考试列表
            List<Exam> exams = examService.getStudentExams(user);
            model.addAttribute("exams", exams);
            model.addAttribute("currentPage", "history");
            return "exam/student-list";
        }
    }

    @GetMapping("/create")
    public String showCreateForm(Model model, HttpSession session) {
        SimpleUser user = (SimpleUser) session.getAttribute("user");
        if (user == null || !UserRole.TEACHER.equals(user.getRole())) {
            return "redirect:/simple-login";
        }
        
        model.addAttribute("exam", new Exam());
        model.addAttribute("classes", classService.getTeacherClasses(user));
        return "exam/form";
    }

    @PostMapping("/create")
    public String createExam(@RequestParam String examName,
                           @RequestParam String subject,
                           @RequestParam Long classId,
                           @RequestParam LocalDateTime examDate,
                           @RequestParam(required = false) String description,
                           HttpSession session,
                           RedirectAttributes redirectAttributes) {
        try {
            log.debug("Received create exam request - examName: {}, subject: {}, classId: {}, examDate: {}, description: {}", 
                     examName, subject, classId, examDate, description);
            
            SimpleUser user = (SimpleUser) session.getAttribute("user");
            log.debug("User: {}", user);
            log.debug("User role: {}", user != null ? user.getRole() : "null");
            if (user == null || !UserRole.TEACHER.equals(user.getRole())) {
                log.warn("Unauthorized access attempt - user: {}", user);
                return "redirect:/simple-login";
            }
            
            // 获取班级信息
            log.debug("Fetching class with ID: {}", classId);
            ClassEntity classEntity = classService.getClass(classId);
            if (classEntity == null) {
                log.warn("Class not found with ID: {}", classId);
                redirectAttributes.addFlashAttribute("error", "班级不存在");
                return "redirect:/exam/create";
            }
            log.debug("Found class: {}", classEntity);
            
            Exam exam = new Exam();
            exam.setExamName(examName);
            exam.setSubject(subject);
            exam.setDescription(description);
            exam.setExamDate(examDate);
            exam.setTeacher(user);
            exam.setClassEntity(classEntity);
            exam.setStatus("ACTIVE");
            exam.setCreatedAt(LocalDateTime.now());
            exam.setUpdatedAt(LocalDateTime.now());
            
            log.debug("Saving exam: {}", exam);
            examService.save(exam);
            redirectAttributes.addFlashAttribute("success", "考试创建成功！");
            return "redirect:/exam/manage";
        } catch (Exception e) {
            log.error("Error creating exam", e);
            redirectAttributes.addFlashAttribute("error", "创建考试失败：" + e.getMessage());
            return "redirect:/exam/create";
        }
    }

    @GetMapping("/edit/{id}")
    public String showEditForm(@PathVariable Long id, Model model, HttpSession session) {
        SimpleUser user = (SimpleUser) session.getAttribute("user");
        if (user == null || !"TEACHER".equals(user.getRole())) {
            return "redirect:/simple-login";
        }
        
        model.addAttribute("exam", examService.getExam(id));
        model.addAttribute("classes", classService.getTeacherClasses(user));
        return "exam/form";
    }

    @PostMapping("/edit/{id}")
    public String updateExam(@PathVariable Long id,
                           @ModelAttribute Exam exam,
                           HttpSession session,
                           RedirectAttributes redirectAttributes) {
        try {
            SimpleUser user = (SimpleUser) session.getAttribute("user");
            if (user == null || !"TEACHER".equals(user.getRole())) {
                return "redirect:/simple-login";
            }
            
            exam.setId(id);
            examService.updateExam(exam);
            redirectAttributes.addFlashAttribute("success", "考试更新成功");
            return "redirect:/exam/list";
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "更新失败：" + e.getMessage());
            return "redirect:/exam/edit/" + id;
        }
    }

    @PostMapping("/delete/{id}")
    public String deleteExam(@PathVariable Long id,
                           HttpSession session,
                           RedirectAttributes redirectAttributes) {
        try {
            SimpleUser user = (SimpleUser) session.getAttribute("user");
            if (user == null || !"TEACHER".equals(user.getRole())) {
                return "redirect:/simple-login";
            }
            
            examService.deleteExam(id);
            redirectAttributes.addFlashAttribute("success", "考试删除成功");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "删除失败：" + e.getMessage());
        }
        return "redirect:/exam/manage";
    }

    @GetMapping("/detail/{id}")
    public String showExamDetail(@PathVariable Long id, Model model) {
        Exam exam = examService.getExam(id);
        model.addAttribute("exam", exam);
        model.addAttribute("records", examRecordService.getExamRecords(exam));
        return "exam/detail";
    }

    @GetMapping("/grade")
    public String showGradePage(Model model, HttpSession session) {
        SimpleUser user = (SimpleUser) session.getAttribute("user");
        if (user == null || !UserRole.TEACHER.equals(user.getRole())) {
            return "redirect:/simple-login";
        }
        
        List<ClassEntity> classes = classService.getTeacherClasses(user);
        List<Exam> exams = examService.getTeacherExams(user);
        
        model.addAttribute("classes", classes);
        model.addAttribute("exams", exams);
        model.addAttribute("currentPage", "grade");
        return "exam/grade";
    }

    @PostMapping("/grade")
    public String gradeExam(@RequestParam("examImage") MultipartFile examImage,
                           @RequestParam("examId") Long examId,
                           @RequestParam("studentName") String studentName,
                           @RequestParam(value = "answerRequirements", required = false) String answerRequirements,
                           HttpSession session,
                           RedirectAttributes redirectAttributes) {
        try {
            log.debug("开始批改考试 - examId: {}, studentName: {}", examId, studentName);
            
            SimpleUser user = (SimpleUser) session.getAttribute("user");
            if (user == null || !UserRole.TEACHER.equals(user.getRole())) {
                log.warn("未授权的访问尝试 - user: {}", user);
                return "redirect:/simple-login";
            }

            if (examImage.isEmpty()) {
                log.warn("未上传试卷图片");
                redirectAttributes.addFlashAttribute("error", "请上传试卷图片");
                return "redirect:/exam/grade";
            }

            Exam exam = examService.getExam(examId);
            if (exam == null) {
                log.warn("未找到考试 - examId: {}", examId);
                redirectAttributes.addFlashAttribute("error", "未找到指定的考试");
                return "redirect:/exam/grade";
            }

            ExamRecord record = new ExamRecord();
            record.setExam(exam);
            record.setTeacher(user);
            record.setStudentName(studentName);
            record.setAnswerRequirements(answerRequirements);
            record.setStatus("PENDING");

            log.debug("创建考试记录: {}", record);
            record = examRecordService.createRecord(record, examImage);
            
            log.debug("开始AI批改");
            examRecordService.gradeExam(record);
            
            redirectAttributes.addFlashAttribute("success", "试卷批改成功！");
            return "redirect:/exam/result/" + record.getId();
        } catch (Exception e) {
            log.error("批改考试失败", e);
            redirectAttributes.addFlashAttribute("error", "批改失败：" + e.getMessage());
            return "redirect:/exam/grade";
        }
    }

    @GetMapping("/history")
    public String showHistory(Model model, HttpSession session) {
        SimpleUser user = (SimpleUser) session.getAttribute("user");
        if (user == null) {
            return "redirect:/simple-login";
        }
        
        List<ExamRecord> records = examRecordService.getUserRecords(user);
        model.addAttribute("records", records);
        model.addAttribute("currentPage", "history");
        return "exam/history";
    }

    @GetMapping("/result/{id}")
    public String showResult(@PathVariable Long id, Model model) {
        ExamRecord record = examRecordService.getRecord(id);
        model.addAttribute("record", record);
        return "exam/result";
    }

    @PostMapping("/submit")
    public String submitExam(@RequestParam Long examId,
                           @RequestParam String studentName,
                           @RequestParam MultipartFile examImage,
                           RedirectAttributes redirectAttributes) {
        try {
            Exam exam = examService.getExam(examId);
            ExamRecord record = new ExamRecord();
            record.setExam(exam);
            record.setStudentName(studentName);
            
            examRecordService.createRecord(record, examImage);
            redirectAttributes.addFlashAttribute("success", "试卷提交成功");
            return "redirect:/exam/detail/" + examId;
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "提交失败：" + e.getMessage());
            return "redirect:/exam/detail/" + examId;
        }
    }

    @GetMapping("/view/{id}")
    public String viewExamImage(@PathVariable Long id, Model model) {
        ExamRecord record = examRecordService.getRecord(id);
        model.addAttribute("record", record);
        return "exam/view";
    }

    @GetMapping("/manage")
    public String showManagePage(Model model, HttpSession session) {
        SimpleUser user = (SimpleUser) session.getAttribute("user");
        if (user == null) {
            return "redirect:/simple-login";
        }
        
        List<Exam> exams = examService.findByTeacherId(user.getId());
        model.addAttribute("exams", exams);
        return "exam/manage";
    }
} 